import { ActionReducerMapBuilder, AsyncThunk, createAsyncThunk, createSlice, PayloadAction } from '@reduxjs/toolkit';
import { ConsultIllness, ConsultMedicine, ConsultOrderPre, ConsultOrderPreParams, Medicine, MedicineDetail, MedicinePage, MedicineParams, PartialConsult, PaymentParams } from '@/type/ConsultType';
import type { ConsultType } from '@/enum';
import { uploadAPI, UploadResponse } from '@/API/commonAPI';
import type { AsyncThunkConfig } from '@reduxjs/toolkit/dist/createAsyncThunk';
import { Patient } from '@/type/PatientType';
import { createConsultOrderAPI, fetchConsultOrderPreAPI, fetchMedicineListAPI, fetchOrderDetailAPI, findMedicineDetailAPI, paymentConsultOrderAPI } from '@/API/consultAPI';
import { cancelOrderAPI, deleteOrderAPI, fetchOrderListAPI } from '@/API/ConsultOrder';
import { OrderItem, OrderPage, OrderParams } from '@/type/ConsultOrder';


type SetConsultTypeAction = { payload: ConsultType, type: string }
type SetIllnessTypeAction = { payload: 0 | 1, type: string }
type SetDepIdAction = { payload: string, type: string }
type SetConsultIllnessInfoAction = { payload: ConsultIllness, type: string }
type SetPatientIdAction = { payload: Patient, type: string }
type SetConsultMedicineAction = { payload: ConsultMedicine, type: string }
type SetMedicinesAction = { payload: Medicine[], type: string }

type InitialState = {
  consultInfo: PartialConsult
  medicineDetail: MedicineDetail,
  orderDetail: OrderItem
}

const initialState: InitialState = {
  consultInfo: JSON.parse(localStorage.getItem('consultInfo') as string) || {},
  medicineDetail: {} as MedicineDetail,
  orderDetail: {} as OrderItem,
};

/**
 * @description 上传图片的异步函数
 * */
export const upload: AsyncThunk<UploadResponse, FormData, AsyncThunkConfig> = createAsyncThunk('upload', async (file, { rejectWithValue }) => {
  try {
    const { data } = await uploadAPI(file);
    return data;
  } catch (error: any) {
    return rejectWithValue(error.message);
  }
});

/**
 * @description 获取订单预支付信息的异步函数
 * */
export const fetchConsultOrderPre: AsyncThunk<ConsultOrderPre, ConsultOrderPreParams, AsyncThunkConfig> = createAsyncThunk('fetchConsultOrderPre', async (params, { rejectWithValue }) => {
  try {
    const { data } = await fetchConsultOrderPreAPI(params);
    return data;
  } catch (error: any) {
    return rejectWithValue(error.message);
  }
});

/**
 * @description 保存提交订单的异步函数
 * */
export const createConsultOrder: AsyncThunk<{ id: string }, PartialConsult, AsyncThunkConfig> = createAsyncThunk('createConsultOrder', async (partialConsult, { rejectWithValue }) => {
  try {
    const { data } = await createConsultOrderAPI(partialConsult);
    return data;
  } catch (error: any) {
    return rejectWithValue(error.message);
  }
});

/**
 * @description 支付的异步函数
 * */
export const paymentConsultOrder: AsyncThunk<string, PaymentParams, AsyncThunkConfig> = createAsyncThunk('paymentConsultOrder', async (paymentParams, { rejectWithValue }) => {
  try {
    const { data: { payUrl } } = await paymentConsultOrderAPI(paymentParams);
    return payUrl;
  } catch (error: any) {
    return rejectWithValue(error.message);
  }
});

/**
 * @description 查询药品列表的回调函数
 * */
export const fetchMedicineList: AsyncThunk<MedicinePage, MedicineParams, AsyncThunkConfig> = createAsyncThunk('fetchMedicineList', async (medicineParams, { rejectWithValue }) => {
  try {
    const { data } = await fetchMedicineListAPI(medicineParams);
    data.rows.forEach((item) => item.quantity = '0');
    return data;
  } catch (error: any) {
    return rejectWithValue(error.message);
  }
});

/**
 * @description 查询药品详情的异步函数
 * */

export const findMedicineDetail: AsyncThunk<MedicineDetail, string, AsyncThunkConfig> = createAsyncThunk('findMedicineDetail', async (id, { rejectWithValue }) => {
  try {
    const { data } = await findMedicineDetailAPI(id);
    data.quantity = '1';
    return data;
  } catch (error: any) {
    return rejectWithValue(error.message);
  }
});

/**
 * @description 获取订单列表的异步函数
 * */
export const fetchOrderList: AsyncThunk<OrderPage, OrderParams, AsyncThunkConfig> = createAsyncThunk('fetchOrderList', async (params, { rejectWithValue }) => {
  try {
    const { data } = await fetchOrderListAPI(params);
    return data;
  } catch (error: any) {
    return rejectWithValue(error.message);
  }
});

/**
 * @description 删除订单的异步函数
 * */
export const deleteOrder: AsyncThunk<'订单删除成功', string, AsyncThunkConfig> = createAsyncThunk('deleteOrder', async (id, { rejectWithValue }) => {
  try {
    await deleteOrderAPI(id);
    return '订单删除成功';
  } catch (error: any) {
    return rejectWithValue(error.message);
  }
});

/**
 * @description 取消订单的异步函数
 * */
export const cancelOrder: AsyncThunk<'订单取消成功', string, AsyncThunkConfig> = createAsyncThunk('cancelOrder', async (id, { rejectWithValue }) => {
  try {
    await cancelOrderAPI(id);
    return '订单取消成功';
  } catch (error: any) {
    return rejectWithValue(error.message);
  }
});

/**
 * @description 查询订单详情信息的异步函数
 * */
export const fetchOrderDetail: AsyncThunk<OrderItem, string, AsyncThunkConfig> = createAsyncThunk('fetchOrderDetail', async (orderId, { rejectWithValue }) => {
  try {
    const { data } = await fetchOrderDetailAPI(orderId);
    return data;
  } catch (error: any) {
    return rejectWithValue(error.message);
  }
});

const consultStore = createSlice({
  name: 'consultStore',
  initialState,
  reducers: {
    /**
     * 第一步记录问诊类型：1找医生、2极速问诊、3开药问诊
     * */
    setConsultType(state: InitialState, action: SetConsultTypeAction) {
      const { payload } = action;
      state.consultInfo.type = payload;
      console.log(`问诊类型是${payload}`);
    },

    /**
     * 第二步：记录极速问诊的类型 0普通 1三甲
     * */
    setIllnessType(sate: InitialState, action: SetIllnessTypeAction) {
      const { payload } = action;
      sate.consultInfo.illnessType = payload;
      console.log(`极速问诊类型是${payload}`);
    },
    /**
     * 第三步：记录就诊的科室ID
     * */
    setDepId(state: InitialState, action: SetDepIdAction) {
      const { payload } = action;
      state.consultInfo.depId = payload;
      console.log(`选择的科室ID是${payload}`);
    },

    /**
     * 第四步:记录极速问诊病情描述信息
     * */
    setConsultIllnessInfo(state: InitialState, action: SetConsultIllnessInfoAction) {
      const { illnessDesc, illnessTime, pictures, consultFlag } = action.payload;
      // 疾病描述
      state.consultInfo.illnessDesc = illnessDesc;
      // 患病时间
      state.consultInfo.illnessTime = illnessTime;
      // 病情图片数组
      state.consultInfo.pictures = pictures;
      // 是否就诊过
      state.consultInfo.consultFlag = consultFlag;
      console.table(action.payload);
    },

    /**
     * 第五步:记录患者ID
     * */
    setPatientId(state: InitialState, action: SetPatientIdAction) {
      const { id } = action.payload;
      state.consultInfo.patientId = id;
      console.table(action.payload);
    },


    /**
     * @description 记录开药问诊病情描述信息
     **/
    setConsultMedicineInfo(state: InitialState, action: SetConsultMedicineAction) {
      const { illnessDesc, renalFunction, liverFunction, allergicHistory, fertilityStatus, pictures } = action.payload;
      // 患者症状描述
      state.consultInfo.illnessDesc = illnessDesc;
      // 肝功能
      state.consultInfo.renalFunction = renalFunction;
      // 肾功能
      state.consultInfo.liverFunction = liverFunction;
      // 过敏史
      state.consultInfo.allergicHistory = allergicHistory;
      // 生育状态及计划
      state.consultInfo.fertilityStatus = fertilityStatus;
      // 病例信息图片数组
      state.consultInfo.pictures = pictures;
      console.table(action.payload);
    },

    /**
     * 设置选中的药品列表
     * */
    setMedicines(state: InitialState, action: SetMedicinesAction) {
      const { payload } = action;
      state.consultInfo.medicines = payload;
      console.log(payload);
    },

    changeMedicineDetailQuantity(state: InitialState) {
      state.medicineDetail.quantity = Number(state.medicineDetail.quantity) + 1 + '';
    },
    /**
     * @description 清除问诊信息
     * */
    clearConsultInfo(state) {
      state.consultInfo = {};
    },
  },
  extraReducers(builder: ActionReducerMapBuilder<InitialState>) {
    builder.addCase(findMedicineDetail.fulfilled, (state: InitialState, action: PayloadAction<MedicineDetail>) => {
      state.medicineDetail = action.payload;
    });
    builder.addCase(fetchOrderDetail.fulfilled, (state: InitialState, action: PayloadAction<OrderItem>) => {
      state.orderDetail = action.payload;
    });
  },
});

export const { setConsultType, setIllnessType, setDepId, setConsultIllnessInfo, setPatientId, clearConsultInfo, setConsultMedicineInfo, setMedicines, changeMedicineDetailQuantity } = consultStore.actions;

export default consultStore.reducer;

